"""
智能会议安排系统 - 完整示例

演示如何使用会议调度环境进行训练和推理
"""

import sys
import os

# 添加路径
sys.path.append(os.path.dirname(os.path.dirname(__file__)))

from agentic_system.environments.env_package.meeting_scheduling import (
    MeetingSchedulingEnv,
    MeetingSchedulingMultiProcessEnv,
    meeting_projection,
    MeetingReward
)
from agentic_system.environments.env_package.meeting_scheduling.env_manager import (
    create_meeting_env_manager
)
from agentic_system.environments.prompts.meeting_prompts import (
    build_full_prompt,
    add_observation_to_messages
)


def example_single_env():
    """示例1: 单环境交互"""
    print("="*80)
    print("示例1: 单环境交互")
    print("="*80 + "\n")

    # 创建环境
    env = MeetingSchedulingEnv(max_steps=20, seed=42)

    # 重置
    observation, info = env.reset()

    print("初始观察:")
    print(observation)
    print(f"\n会议信息:")
    print(f"  主题: {info['meeting_topic']}")
    print(f"  必选人员: {info['required_count']}")
    print(f"  可选人员: {info['optional_count']}")
    print(f"  历史模式: {info['historical_pattern']}")

    # 步骤1: 查询所有人的日程
    print("\n" + "-"*80)
    print("步骤1: 查询日程")
    print("-"*80)

    action1 = {
        'action_type': 'query_calendar',
        'parameters': {
            'persons': env.required_attendees + env.optional_attendees
        }
    }

    obs, reward, done, info = env.step(action1, valid=1)
    print(obs)
    print(f"\n奖励: {reward:.2f}, 完成: {done}")

    # 步骤2: 查询历史
    print("\n" + "-"*80)
    print("步骤2: 查询历史会议")
    print("-"*80)

    action2 = {
        'action_type': 'query_history',
        'parameters': {}
    }

    obs, reward, done, info = env.step(action2, valid=1)
    print(obs)
    print(f"\n奖励: {reward:.2f}, 完成: {done}")

    # 步骤3: 分析并选择时间
    # 假设我们发现周二上午是最优时间
    print("\n" + "-"*80)
    print("步骤3: 选择会议时间")
    print("-"*80)

    # 检查历史偏好时间的可用性
    if info['historical_pattern']:
        preferred_day, preferred_slot = info['historical_pattern']
        print(f"\n历史偏好时间: {preferred_day}, {preferred_slot}")

        # 检查必选人员在该时段的可用性
        all_available = all(
            env.calendar_data[person][preferred_day][preferred_slot] == 'available'
            for person in env.required_attendees
        )

        if all_available:
            print("✓ 所有必选人员在偏好时段都可用")
            selected_day, selected_slot = preferred_day, preferred_slot
        else:
            print("✗ 有必选人员在偏好时段不可用，选择其他时间...")
            # 简单策略：找第一个所有必选人员都可用的时间
            selected_day, selected_slot = None, None
            for day in env.DAYS:
                for slot in env.TIME_SLOTS:
                    if all(env.calendar_data[p][day][slot] == 'available' for p in env.required_attendees):
                        selected_day, selected_slot = day, slot
                        break
                if selected_day:
                    break

        if selected_day:
            action3 = {
                'action_type': 'select_time',
                'parameters': {
                    'day': selected_day,
                    'time_slot': selected_slot
                }
            }

            obs, reward, done, info = env.step(action3, valid=1)
            print(f"\n选择时间: {selected_day}, {selected_slot}")
            print(obs)
            print(f"\n最终奖励: {reward:.2f}")
            print(f"成功: {info.get('won', False)}")


def example_multiprocess_env():
    """示例2: 多进程矢量化环境"""
    print("\n\n" + "="*80)
    print("示例2: 多进程矢量化环境")
    print("="*80 + "\n")

    # 创建矢量化环境
    env = MeetingSchedulingMultiProcessEnv(
        seed=42,
        env_num=4,
        max_steps=20
    )

    print(f"环境数量: {len(env)}")

    # 重置
    observations, infos = env.reset()

    print("\n各环境初始状态:")
    for i, (obs, info) in enumerate(zip(observations, infos)):
        print(f"\n环境{i}: {info['meeting_topic']}")
        print(f"  必选: {info['required_count']}, 可选: {info['optional_count']}")

    # 批量执行动作
    print("\n" + "-"*80)
    print("批量查询日程")
    print("-"*80)

    # 为每个环境准备不同的动作（模拟LLM输出）
    text_actions = [
        '''
        查询所有人的日程
        ```json
        {
            "action_type": "query_calendar",
            "parameters": {
                "persons": ["李明", "王芳", "陈静"]
            }
        }
        ```
        ''',
        '''
        ```json
        {
            "action_type": "query_calendar",
            "parameters": {
                "persons": ["李明", "王芳"]
            }
        }
        ```
        ''',
        '''
        ```json
        {
            "action_type": "query_history",
            "parameters": {}
        }
        ```
        ''',
        '''
        ```json
        {
            "action_type": "query_calendar",
            "parameters": {
                "persons": ["张伟", "周娟", "吴杰"]
            }
        }
        ```
        '''
    ]

    valids = [1, 1, 1, 1]

    observations, rewards, dones, infos = env.step(text_actions, valids)

    print("\n执行结果:")
    for i, (obs, reward, done) in enumerate(zip(observations, rewards, dones)):
        print(f"\n环境{i}:")
        print(f"  奖励: {reward:.2f}")
        print(f"  完成: {done}")
        print(f"  观察: {obs[:100]}...")

    env.close()


def example_with_prompts():
    """示例3: 使用提示词模板"""
    print("\n\n" + "="*80)
    print("示例3: 使用提示词模板构建完整对话")
    print("="*80 + "\n")

    # 用户请求
    user_request = "下周找个时间开产品规划会，必须参加的有李明、王芳，可选参加的有陈静、刘强、赵敏。"

    # 构建初始消息
    messages = build_full_prompt(user_request, use_memory=False)

    print("初始消息列表:")
    for i, msg in enumerate(messages):
        print(f"\n消息{i} [{msg['role']}]:")
        content_preview = msg['content'][:200] + "..." if len(msg['content']) > 200 else msg['content']
        print(content_preview)

    # 模拟Agent响应
    print("\n" + "-"*80)
    print("模拟Agent第一步响应")
    print("-"*80)

    assistant_response = '''
    首先查询所有参会人员的日程。
    ```json
    {
        "action_type": "query_calendar",
        "parameters": {
            "persons": ["李明", "王芳", "陈静", "刘强", "赵敏"]
        }
    }
    ```
    '''

    # 模拟环境观察
    observation = """日程查询结果：

李明的日程：
  Monday: morning:available, afternoon:busy, evening:available
  Tuesday: morning:available, afternoon:available, evening:available
  ...（省略）

王芳的日程：
  Monday: morning:busy, afternoon:available, evening:available
  ...（省略）
"""

    # 添加到消息历史
    messages = add_observation_to_messages(messages, assistant_response, observation)

    print(f"\n更新后消息数: {len(messages)}")
    print(f"\n最后一条消息 [{messages[-1]['role']}]:")
    print(messages[-1]['content'][:300])


def example_reward_evaluation():
    """示例4: 奖励评估"""
    print("\n\n" + "="*80)
    print("示例4: 奖励评估和策略分析")
    print("="*80 + "\n")

    reward_calculator = MeetingReward()

    # 场景A: 理想情况
    print("场景A: 理想情况")
    print("-"*40)

    scores_a = reward_calculator.calculate_reward(
        required_available=3,
        required_total=3,
        optional_available=3,
        optional_total=3,
        historical_match=True,
        negotiations_count=0,
        steps_count=4,
        max_steps=20
    )

    print(f"必选人员: 3/3")
    print(f"可选人员: 3/3")
    print(f"历史匹配: 是")
    print(f"协商次数: 0")
    print(f"\n奖励明细:")
    for key, value in scores_a.items():
        print(f"  {key}: {value:.2f}")

    # 场景B: 需要协商
    print("\n场景B: 需要协商")
    print("-"*40)

    scores_b = reward_calculator.calculate_reward(
        required_available=3,
        required_total=3,
        optional_available=2,
        optional_total=3,
        historical_match=True,
        negotiations_count=1,
        steps_count=6,
        max_steps=20
    )

    print(f"必选人员: 3/3")
    print(f"可选人员: 2/3")
    print(f"历史匹配: 是")
    print(f"协商次数: 1")
    print(f"\n奖励明细:")
    for key, value in scores_b.items():
        print(f"  {key}: {value:.2f}")

    # 场景C: 失败
    print("\n场景C: 失败情况")
    print("-"*40)

    scores_c = reward_calculator.calculate_reward(
        required_available=2,
        required_total=3,
        optional_available=3,
        optional_total=3,
        historical_match=True,
        negotiations_count=0,
        steps_count=4,
        max_steps=20
    )

    print(f"必选人员: 2/3 (缺1人)")
    print(f"可选人员: 3/3")
    print(f"历史匹配: 是")
    print(f"协商次数: 0")
    print(f"\n奖励明细:")
    for key, value in scores_c.items():
        print(f"  {key}: {value:.2f}")

    # 策略评估
    print("\n\n策略评估示例")
    print("-"*40)

    episode_history = [
        {'step': 1, 'action_type': 'query_calendar', 'parameters': {}, 'observation': '', 'reward': 0},
        {'step': 2, 'action_type': 'query_history', 'parameters': {}, 'observation': '', 'reward': 0},
        {'step': 3, 'action_type': 'select_time', 'parameters': {}, 'observation': '', 'reward': 8}
    ]

    final_result = {
        'required_met': True,
        'required_available': 3,
        'required_total': 3,
        'optional_available': 3,
        'optional_total': 3,
        'historical_match': True,
        'negotiations_count': 0
    }

    evaluation = reward_calculator.evaluate_strategy(episode_history, final_result)

    print(f"总步数: {evaluation['total_steps']}")
    print(f"成功: {evaluation['success']}")
    print(f"动作序列: {evaluation['action_sequence']}")
    print(f"\n策略分析:")
    for key, value in evaluation['strategy_analysis'].items():
        print(f"  {key}: {value}")


def example_env_manager():
    """示例5: 使用环境管理器"""
    print("\n\n" + "="*80)
    print("示例5: 环境管理器（集成到框架）")
    print("="*80 + "\n")

    # 配置
    config = {
        'seed': 42,
        'env_num': 2,
        'max_steps': 20,
        'is_train': True,
        'use_memory': False
    }

    # 创建环境管理器
    env_manager = create_meeting_env_manager(config)

    print(f"环境名称: {env_manager.env_name}")
    print(f"环境数量: {len(env_manager.envs)}")

    # 重置
    observations = env_manager.reset()

    print(f"\n观察格式: {observations.keys()}")
    print(f"文本观察: {len(observations['text'])}")

    # 执行步骤
    text_actions = [
        '''
        ```json
        {
            "action_type": "query_calendar",
            "parameters": {"persons": ["李明", "王芳"]}
        }
        ```
        ''',
        '''
        ```json
        {
            "action_type": "query_history",
            "parameters": {}
        }
        ```
        '''
    ]

    observations, rewards, dones, infos = env_manager.step(text_actions)

    print(f"\n奖励: {rewards}")
    print(f"完成标志: {dones}")

    # 成功率评估
    success_results = env_manager.success_evaluator(infos=infos)
    print(f"成功标志: {success_results['success']}")


def main():
    """运行所有示例"""
    print("\n")
    print("#"*80)
    print("#" + " "*78 + "#")
    print("#" + " "*20 + "智能会议安排系统 - 完整示例" + " "*25 + "#")
    print("#" + " "*78 + "#")
    print("#"*80)
    print("\n")

    # 运行各个示例
    example_single_env()
    example_multiprocess_env()
    example_with_prompts()
    example_reward_evaluation()
    example_env_manager()

    print("\n\n" + "="*80)
    print("所有示例运行完毕！")
    print("="*80)


if __name__ == '__main__':
    main()
